from django.http import *
from django.shortcuts import *
from django import forms
from django.template import RequestContext 
from ytbase.helper import *
from ytbase.model.post import *
from ytbase.setting import *
from comment import CommentForm

class PostForm(forms.Form):
    title = forms.CharField(max_length=100)
    tags = forms.CharField(required=False, max_length=100)
    content = forms.CharField(required=False, widget=forms.Textarea)

@authorize(YTPost, OPERATION_ADD)
def add(request, template, redirect_helper=None, filler=None, processors=[], helpers={}):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = YTPost(author=YTUser.get_current_user())
            post.title = form.cleaned_data['title']
            post.content = form.cleaned_data['content']
            post.add_tags( form.cleaned_data['tags'] )
            
            if filler is not None:
                post = filler(post)
            
            post.put()
            redirect = redirect_helper(post)            
            return HttpResponseRedirect(redirect)
    else:
        form = PostForm() # An unbound form

    context = {'form': form}
    rc = RequestContext(request, processors=processors)
    return render_to_response(template, context, rc)

@check_id(YTPost)
@authorize(YTPost, OPERATION_EDIT)
def edit(request, id, template, redirect_helper=None, filler=None, processors=[]):
    if request.method == 'POST':
        form = PostForm(request.POST)
        post = None
        if form.is_valid():
            post = get_by_str_id(YTPost, id)
            post.title = form.cleaned_data['title']
            post.content = form.cleaned_data['content']
            post.add_tags( form.cleaned_data['tags'] )

            if filler is not None:
                post = filler(post)            
            
            post.put()
            redirect = redirect_helper(post)            
            return HttpResponseRedirect(redirect)
    else:
        post = get_by_str_id(YTPost, id)        
        data = {
            'title':post.title,
            'tags':post.get_tag_str(),
            'content':post.content,
        }
        form = PostForm(data)

    context = {'form':form, 'post':post}
    rc = RequestContext(request, processors=processors)
    return render_to_response(template, context, rc)
        
@check_id(YTPost)
@authorize(YTPost, OPERATION_DELETE)
def delete(request, id):
    if request.method == 'POST':
        post = get_by_str_id(YTPost, id)
        post.delete()
        return HttpResponse('Deleted!')
    return HttpResponseNotFound()

@check_id(YTPost)
@authorize(YTPost, OPERATION_ADD)
def promote(request, id):
    if request.method == 'POST':
        post = get_by_str_id(YTPost, id)
        
        if request.ga_user.admin:
            post.points += POINTS_HOT
        else:
            post.points += 1        
        if post.points >= POINTS_HOT:
            post.popular = True
                    
        post.put()
        return HttpResponse('Done!')
    return HttpResponseNotFound()
        
def list(request, template, num_per_page=10, filters=[], filler=None, processors=[]):
    filters = get_common_filters(request) + filters
    posts, page = Paginator(request, YTPost, filters, num_per_page).get_page_objects()
    
    if filler is not None:
        posts = [filler(post) for post in posts]
        
    context = {
        'posts': [fill_post(post) for post in posts],
        'page_info': page,
    }
    rc = RequestContext(request, processors=processors)
    return render_to_response(template, context, rc)
    
@check_id(YTPost)
def display(request, id, template, filler=None, processors=[]):
    post = get_by_str_id(YTPost, id)
    
    if filler is not None:
        post = filler(post)
        
    context = {
        'post':fill_post(post),
        'form':CommentForm()
    }
    rc = RequestContext(request, processors=processors)
    return render_to_response(template, context, rc)

def get_common_filters(request):
    filters = []
    
    if request.GET.has_key('tag'):
        filters.append(lambda q: q.filter('tags =', request.GET['tag']))
        
    filters.append(lambda q: q.order('-date'))
    return filters

def fill_post(post):
    post.auth = get_auth((YTPost, post))
    return post

class PostHanlder(object):
    def __init__(self, request, category, id=None):
        if id:
            self.post = get_by_str_id(YTPost, id)
        else:
            self.post = None
            
        self.request = request
        self.category = category
        
        self.filters = []
        self.filters.append(lambda q: q.filter('category =', CATEGORY))

        if self.request.GET.has_key('tag'):
            self.filters.append(lambda q: q.filter('tags =', request.GET['tag']))
            
    def has_tag(self):
        return self.request.GET.has_key('tag')
    
    def get_posts(self, num_per_page, filters=[]):
        return Paginator(self.request, YTPost, self.filters+filters, num_per_page).get_page_objects()
    
    def delete(self):
        if self.request.method == 'POST':
            self.post.delete()
            return HttpResponse('Deleted!')
        return HttpResponseNotFound()
